package cn.echase.ecare.yinfayun.utils;


import cn.echase.ecare.yinfayun.domain.dto.SortDescDto;

import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;

/**
 * 排序工具类
 * @param <T>
 */
public class ComparaUtils<T> {

    public  Comparator<T> buildComparator(List<SortDescDto> sortDescList, Class<T> clazz) {
        if (sortDescList == null || sortDescList.isEmpty()) {
            return null;
        }

        Comparator<T> comparator = null;
        for (SortDescDto sortDesc : sortDescList) {
            String sortField = sortDesc.getSortColumn();
            String sortOrder = sortDesc.getSort();
            try {
                // 构建 getter 方法名
                String getterMethodName = "get" + sortField.substring(0, 1).toUpperCase() + sortField.substring(1);
                Method getterMethod = clazz.getMethod(getterMethodName);

                Comparator<T> fieldComparator = (e1, e2) -> {
                    try {
                        Comparable<Object> value1 = (Comparable<Object>) getterMethod.invoke(e1);
                        Comparable<Object> value2 = (Comparable<Object>) getterMethod.invoke(e2);
                        if (value1 == null&&value2==null) {
                            return 0;
                        }
                        if (value1 == null&&value2!=null) {
                            return -1;
                        }
                        if (value1 != null&&value2==null) {
                            return 1;
                        }
                        return value1.compareTo(value2);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                };

                if ("desc".equalsIgnoreCase(sortOrder)) {
                    fieldComparator = fieldComparator.reversed();
                }

                if (comparator == null) {
                    comparator = fieldComparator;
                } else {
                    comparator = comparator.thenComparing(fieldComparator);
                }
            } catch (NoSuchMethodException e) {
                // 处理方法不存在的情况
                e.printStackTrace();
            }
        }
        return comparator;
    }

}
